<script lang="ts" setup>
import type { FileInfo as FileItem, ShareItem } from '#/api/openapi';

import { computed, onMounted, ref } from 'vue';

import { usePreferences } from '@vben/preferences';

import {
  Delete,
  Download,
  Folder,
  FolderOpen,
  Recycling as Recycle,
  Time,
} from '@icon-park/vue-next';

import Button from '#/components/fluentui/Button.vue';
import { confirm } from '#/components/global-dialog';
import {
  ShareCodeInputDialog,
  ShareInfoDialog,
} from '#/components/ShareDialog';
import { useShareHistoryStore } from '#/store';
import { downloadFile } from '#/utils/download';
import { getFileCategory, getFileIcon } from '#/utils/icon';

const { isDark } = usePreferences();
const shareHistoryStore = useShareHistoryStore();

// 分享码相关状态
const showShareCodeDialog = ref(false);
const showShareInfoDialog = ref(false);
const shareInfo = ref<ShareItem>();

// 获取所有分享历史记录
const shareHistory = computed(() => shareHistoryStore.getAllHistory);

// 获取统计信息
const stats = computed(() => shareHistoryStore.getStats);

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};

// 删除分享历史记录
const deleteShareHistory = async (id: string) => {
  if (await confirm('确定要删除这条分享历史记录吗？')) {
    shareHistoryStore.removeShareHistory(id);
  }
};

// 清空所有历史记录
const clearAllHistory = async () => {
  if (await confirm('确定要清空所有分享历史记录吗？此操作不可撤销。')) {
    shareHistoryStore.clearHistory();
  }
};

// 清理过期记录
const clearExpiredShares = () => {
  shareHistoryStore.clearExpiredShares();
};

// 分享码相关功能
const openShareCodeDialog = () => {
  showShareCodeDialog.value = true;
};

const handleShareFound = (shareData: ShareItem) => {
  shareInfo.value = shareData;
  console.log('分享信息:', shareData);

  // 保存到分享历史记录
  if (shareData.code) {
    shareHistoryStore.addShareHistory(shareData.code, shareData);
  }

  showShareInfoDialog.value = true;
};

const handleShareError = (errorMessage: string) => {
  console.error('分享码错误:', errorMessage);
};

const handleDownloadFile = (code: string, file: FileItem) => {
  downloadFile(code, file);

  // 如果有当前的分享信息，记录下载
  if (shareInfo.value?.code) {
    shareHistoryStore.recordDownload(shareInfo.value.code, file.id);
  }
};

const handleDownloadFiles = (code: string, files: FileItem[]) => {
  console.log('批量下载文件:', files);
  files.forEach((file) => {
    downloadFile(code, file);
    // 记录每个文件的下载
    if (shareInfo.value?.code) {
      shareHistoryStore.recordDownload(shareInfo.value.code, file.id);
    }
  });
};

// 页面挂载时清理过期记录
onMounted(() => {
  clearExpiredShares();
});
</script>

<template>
  <div
    class="bg-background text-foreground mx-auto min-h-screen max-w-7xl px-6 py-8"
    :data-theme="isDark ? 'dark' : 'light'"
  >
    <!-- 页面标题 -->
    <div class="mb-8 text-center">
      <h1 class="mb-3 text-4xl font-bold">取件记录</h1>
      <p class="text-lg text-gray-600 dark:text-gray-300">
        查看和管理您访问过的分享记录
      </p>

      <!-- 使用分享码按钮 -->
      <div class="mt-4 flex justify-center">
        <Button @click="openShareCodeDialog" appearance="primary" size="large">
          <template #start>
            <Recycle />
          </template>
          使用分享码
        </Button>
      </div>
    </div>

    <!-- 统计信息卡片 -->
    <div class="mb-8 grid grid-cols-1 gap-4 md:grid-cols-3">
      <div
        class="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800"
      >
        <div class="flex items-center">
          <Folder class="h-8 w-8 text-blue-600" />
          <div class="ml-4">
            <p class="text-sm text-gray-600 dark:text-gray-400">访问过的分享</p>
            <p class="text-2xl font-bold">{{ stats.total }}</p>
          </div>
        </div>
      </div>

      <div
        class="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800"
      >
        <div class="flex items-center">
          <FolderOpen class="h-8 w-8 text-green-600" />
          <div class="ml-4">
            <p class="text-sm text-gray-600 dark:text-gray-400">文件总数</p>
            <p class="text-2xl font-bold">{{ stats.totalFiles }}</p>
          </div>
        </div>
      </div>

      <div
        class="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800"
      >
        <div class="flex items-center">
          <Download class="h-8 w-8 text-purple-600" />
          <div class="ml-4">
            <p class="text-sm text-gray-600 dark:text-gray-400">下载次数</p>
            <p class="text-2xl font-bold">{{ stats.totalDownloads }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="mb-6 flex gap-3">
      <Button @click="clearExpiredShares" appearance="subtle" size="medium">
        <template #start>
          <Delete />
        </template>
        清理过期记录
      </Button>
      <Button @click="clearAllHistory" appearance="subtle" size="medium">
        <template #start>
          <Delete />
        </template>
        清空所有记录
      </Button>
    </div>

    <!-- 分享历史列表 -->
    <div v-if="shareHistory.length > 0" class="space-y-4">
      <div
        v-for="item in shareHistory"
        :key="item.id"
        class="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800"
      >
        <!-- 分享信息头部 -->
        <div class="mb-4 flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <div
              class="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900"
            >
              <span class="text-sm font-bold text-blue-800 dark:text-blue-200">
                {{ item.shareCode }}
              </span>
            </div>
            <div>
              <h3 class="text-lg font-semibold">
                分享码: {{ item.shareCode }}
              </h3>
              <div
                class="flex items-center space-x-4 text-sm text-gray-600 dark:text-gray-400"
              >
                <span class="flex items-center">
                  <Time class="mr-1 h-4 w-4" />
                  {{ item.formattedTime }}
                </span>
                <span>{{ item.shareItem.files?.length || 0 }} 个文件</span>
                <span v-if="item.downloadCount">
                  已下载 {{ item.downloadCount }} 次
                </span>
              </div>
            </div>
          </div>
          <Button
            icon-only
            @click="deleteShareHistory(item.id)"
            appearance="subtle"
          >
            <Delete class="text-red-600/90" size="18" />
          </Button>
        </div>

        <!-- 分享消息 -->
        <div
          v-if="item.shareItem.messages && item.shareItem.messages.length > 0"
          class="mb-4 rounded-lg bg-gray-50 p-3 dark:bg-gray-700"
        >
          <p class="text-sm text-gray-700 dark:text-gray-300">
            {{ item.shareItem.messages[0]?.content }}
          </p>
        </div>

        <!-- 文件列表 -->
        <div
          v-if="item.shareItem.files && item.shareItem.files.length > 0"
          class="space-y-2"
        >
          <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300">
            包含文件:
          </h4>
          <div class="grid grid-cols-1 gap-3 lg:grid-cols-2">
            <div
              v-for="file in item.shareItem.files"
              :key="file.id"
              class="flex items-center justify-between rounded-lg border border-gray-100 bg-gray-50 p-3 dark:border-gray-600 dark:bg-gray-700"
            >
              <div class="flex items-center space-x-3">
                <component
                  :is="getFileIcon(file.fileName)"
                  class="h-5 w-5 text-blue-600"
                />
                <div class="min-w-0 flex-1">
                  <p class="truncate text-sm font-medium">
                    {{ file.fileName }}
                  </p>
                  <div class="flex items-center gap-2 text-xs text-gray-500">
                    <span>{{ formatFileSize(file.fileSize || 0) }}</span>
                    <span>
                      {{
                        getFileCategory(
                          file.fileName?.split('.').pop()?.toLowerCase() || '',
                        )
                      }}
                    </span>
                  </div>
                </div>
              </div>
              <Button
                @click="downloadFile(item.shareCode, file)"
                appearance="primary"
                size="small"
              >
                下载
              </Button>
            </div>
          </div>
        </div>

        <!-- 过期时间提示 -->
        <div
          v-if="item.shareItem.expiryTime"
          class="mt-4 text-xs text-gray-500 dark:text-gray-400"
        >
          过期时间: {{ new Date(item.shareItem.expiryTime).toLocaleString() }}
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div
      v-else
      class="rounded-lg border border-gray-200 bg-white p-12 text-center dark:border-gray-700 dark:bg-gray-800"
    >
      <div class="flex items-center justify-center">
        <Folder size="38" class="mx-auto text-gray-400" />
      </div>
      <h3 class="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">
        暂无分享历史
      </h3>
      <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
        使用分享码获取文件后，历史记录将显示在这里
      </p>
    </div>

    <!-- 分享码输入弹窗 -->
    <ShareCodeInputDialog
      v-model="showShareCodeDialog"
      @share-found="handleShareFound"
      @error="handleShareError"
    />

    <!-- 分享信息展示弹窗 -->
    <ShareInfoDialog
      v-model="showShareInfoDialog"
      :share-info="shareInfo"
      @download-file="handleDownloadFile"
      @download-all="handleDownloadFiles"
    />
  </div>
</template>
